package com.example.libary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.libary.entity.Book;
import com.example.libary.mapper.BookMapper;
import com.example.libary.service.BookService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 图书服务实现类
 */
@Service
@RequiredArgsConstructor
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    
    private final BookMapper bookMapper;

    @Override
    public Page<Book> page(Page<Book> page, String name, String author, Long categoryId, String status) {
        // 使用自定义的关联查询方法
        return bookMapper.selectBookPageWithCategory(page, name, author, categoryId, status);
    }

    @Override
    public Book getByIsbn(String isbn) {
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Book::getIsbn, isbn);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, String status) {
        Book book = new Book();
        book.setId(id);
        book.setStatus(status);
        return updateById(book);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAvailable(Long id, Integer available) {
        Book book = getById(id);
        if (book == null) {
            return false;
        }
        
        // 可借数量不能小于0或大于总数量
        if (available < 0 || available > book.getTotal()) {
            return false;
        }
        
        book.setAvailable(available);
        // 更新状态
        if (available == 0) {
            book.setStatus("1"); // 已借出
        } else if (available > 0 && "1".equals(book.getStatus())) {
            book.setStatus("0"); // 可借
        }
        
        return updateById(book);
    }
} 